package net.jiastudy.biz.sys.util;

import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.jiastudy.biz.sys.entity.Permission;
import net.jiastudy.biz.sys.entity.PermissionRoot;

public class ReaderPermissionConfig {
	private static final Logger logger = LoggerFactory
			.getLogger(ReaderPermissionConfig.class);
	
	public static PermissionRoot readerConfig() {
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(
					ReaderPermissionConfig.class
							.getResourceAsStream("/config/permissionConfig.xml"),
					"UTF-8");
			JAXBContext jaxbContext = JAXBContext.newInstance(PermissionRoot.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			PermissionRoot permissionConfig = (PermissionRoot) jaxbUnmarshaller.unmarshal(inputStreamReader);
			return permissionConfig;
		} catch (Exception e) {
			logger.error("读取权限配置出错：" + e);
			e.printStackTrace();
			return null;
		}
	}
	
	private static List<Permission> getPermissions(List<Permission> list){
		List<Permission> permissions = new ArrayList<Permission>();		
		for(Permission permission:list){			
			List<Permission> subPermissions = permission.getSubpermissions();
			if(null != subPermissions && subPermissions.size()>0){
				permissions.addAll(subPermissions);
				permissions.addAll(getPermissions(subPermissions));
			}
		}
		return permissions;
	}
	
	public static List<Permission> getPermissions(PermissionRoot config){
		List<Permission> list = config.getPermissions();
		List<Permission> permissions =new ArrayList<Permission>();
		permissions.addAll(list);
		permissions.addAll(getPermissions(list));
		return permissions;
	}
	
	public static Set<String> getPermissionCodes(PermissionRoot config){
		List<Permission> permissions =  getPermissions(config);
		Set<String> codes = new HashSet<>();
		for (Permission permission : permissions) {
			codes.add(permission.getCode());
		}		
		return codes;
	}
	
	public static void main(String args[]) {
		try {
			PermissionRoot config = ReaderPermissionConfig.readerConfig();
			Set<String> enames= ReaderPermissionConfig.getPermissionCodes(config);
			for (String e : enames) {
				logger.debug(e);
			}
			logger.debug(config.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
